package loginlogic

import (
	"context"
	"time"
	"zhongxc.cc/admin-common/errs"
	"zhongxc.cc/admin-common/tools"
	userdomain "zhongxc.cc/admin-user/internal/domain/user"
	"zhongxc.cc/admin-user/internal/svc"
	"zhongxc.cc/grpc-common/admin-user/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	sysUserDomain *userdomain.SysUserDomain
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:           ctx,
		svcCtx:        svcCtx,
		Logger:        logx.WithContext(ctx),
		sysUserDomain: userdomain.NewSysUserDomain(svcCtx.Db),
	}
}

func (l *LoginLogic) Login(in *user.LoginReq) (*user.LoginRes, error) {
	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()

	sysUser, err := l.sysUserDomain.FindByName(ctx, in.Username, in.Password)
	if err != nil {
		logx.Error(err)
		return nil, errs.GrpcError(errs.NewError(200200, err.Error()))
	}
	logx.Info(sysUser)
	token, _ := tools.GenToken(sysUser.UserId, sysUser.Username)
	loginUser := &user.LoginUserInfo{}
	loginUser.UserId = sysUser.UserId
	loginUser.Username = sysUser.Username
	loginUser.Email = sysUser.Email
	loginUser.Avatar = sysUser.Avatar
	loginUser.AvatarUrl = sysUser.Avatar
	loginUser.Remark = sysUser.Remark
	loginRes := &user.LoginRes{
		User:         loginUser,
		AccessToken:  token,
		RefreshToken: "",
	}
	return loginRes, nil
}
